{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "monetary-enhancement",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "defined \u001b[32mclass\u001b[39m \u001b[36mIntSet\u001b[39m\r\n",
       "defined \u001b[32mobject\u001b[39m \u001b[36mEmpty\u001b[39m\r\n",
       "defined \u001b[32mclass\u001b[39m \u001b[36mNonEmpty\u001b[39m\r\n",
       "\u001b[36mt1\u001b[39m: \u001b[32mNonEmpty\u001b[39m = {.3.}\r\n",
       "\u001b[36mt2\u001b[39m: \u001b[32mIntSet\u001b[39m = {.3{.4.}}\r\n",
       "\u001b[36mt3\u001b[39m: \u001b[32mIntSet\u001b[39m = {{.2.}3{.4.}}"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "abstract class IntSet {\n",
    "    def incl(x:Int):IntSet\n",
    "    def contains(x:Int):Boolean\n",
    "}\n",
    "\n",
    "object Empty extends IntSet {//如果使用object 就可以不用new！\n",
    "    def contains(x:Int):Boolean = false\n",
    "    def incl(x:Int):IntSet = new NonEmpty(x,Empty,Empty)\n",
    "    override def toString = \".\"\n",
    "}\n",
    "\n",
    "class NonEmpty(elem: Int,left: IntSet,right: IntSet) extends IntSet {\n",
    "    def contains(x:Int):Boolean = {\n",
    "        if (x < elem) left contains x\n",
    "        else if(x > elem) right contains x\n",
    "        else true\n",
    "    }\n",
    "    \n",
    "    def incl(x:Int): IntSet ={\n",
    "        if (x < elem) new NonEmpty(elem,left incl x,right)\n",
    "        else if(x > elem) new NonEmpty(elem,left,right incl x)\n",
    "        else this\n",
    "    }\n",
    "    \n",
    "    override def toString = \"{\" + left + elem + right + \"}\"\n",
    "}\n",
    "\n",
    "val t1 = new NonEmpty(3,Empty,Empty)\n",
    "val t2 = t1 incl 4\n",
    "val t3 = t2 incl 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "sacred-energy",
   "metadata": {},
   "outputs": [],
   "source": [
    "//如果使用object 就可以不用new！"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Scala",
   "language": "scala",
   "name": "scala"
  },
  "language_info": {
   "codemirror_mode": "text/x-scala",
   "file_extension": ".scala",
   "mimetype": "text/x-scala",
   "name": "scala",
   "nbconvert_exporter": "script",
   "version": "2.11.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
